//
//  CBDeviceViewController.m
//  CROSBY
//
//  Created by Harvey on 2017/10/5.
//  Copyright © 2017年 Haley. All rights reserved.
//

#import "CBDeviceViewController.h"

#import "ProgressHUD.h"
#import "GWPeripheral.h"
#import "MJRefresh.h"
#import "BluetoothManager.h"

#define kServiceUUID @"FFF0"
#define kCharacteristicUUID @"FFF1"

@interface CBDeviceViewController ()<UITableViewDataSource,UITableViewDelegate,BluetoothManagerDelegate>

@property (strong, nonatomic) UIView            *topView;
@property (strong, nonatomic) UILabel           *tipLabel;
@property (strong, nonatomic) UITableView       *tableView;
@property (strong, nonatomic) UIView            *bottomView;
@property (strong, nonatomic) UIButton          *connectBtn;
@property (strong, nonatomic) UIButton          *disconnectBtn;

@property (strong, nonatomic)   NSMutableArray              *deviceArray;
@property (strong, nonatomic) NSMutableArray            *selectedArray;

@end

@implementation CBDeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = showText(@"连接设备");
    
    [self initTopView];
    
    [self initTableView];
    
    [self initBottomView];
    
    BOOL flag = [[NSUserDefaults standardUserDefaults] boolForKey:kShowedFirstLanguage];
    if (!flag) {
        [self showChoseLanguageView];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kShowedFirstLanguage];
    }
}

- (void)setupLanguage
{
    self.navigationItem.title = showText(@"连接设备");
    
    self.tipLabel.text = showText(@"选择你的设备");
    [self.connectBtn setTitle:showText(@"开始连接") forState:UIControlStateNormal];
    [self.disconnectBtn setTitle:showText(@"断开连接") forState:UIControlStateNormal];
}

- (void)initBgView
{
    
}

- (void)initTopView
{
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 40)];
    self.topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.topView];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, kWidth-60, 40)];
    label.text = showText(@"选择你的设备");
    self.tipLabel = label;
    [self.topView addSubview:label];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 39, kWidth, 0.5)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [self.topView addSubview:lineView];
}

- (void)initTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, kWidth, kHeight-64-40-50-kTopSafeHeight-kBottomSafeHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 64;
    self.tableView.tableFooterView = [UIView new];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDeviceList)];
    header.lastUpdatedTimeLabel.hidden = YES;
    // 隐藏状态
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;
    [self.tableView.mj_header beginRefreshing];
    
    [self.view addSubview:self.tableView];
}

- (void)initBottomView
{
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kHeight-64-kTopSafeHeight-50-kBottomSafeHeight, kWidth, 50)];
    bottomView.backgroundColor = [UIColor whiteColor];
    self.bottomView = bottomView;
    [self.view addSubview:self.bottomView];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 0.5)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [self.bottomView addSubview:lineView];
    
    UIButton *connectBtn = [[UIButton alloc] initWithFrame:CGRectMake((kWidth-240)*0.5, 5, 240, 40)];
    [connectBtn setTitle:showText(@"开始连接") forState:UIControlStateNormal];
    [connectBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    connectBtn.layer.cornerRadius = 5;
    connectBtn.layer.borderColor = [UIColor grayColor].CGColor;
    connectBtn.layer.borderWidth = 0.5;
    connectBtn.layer.masksToBounds = YES;
    [connectBtn addTarget:self action:@selector(connectClick) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:connectBtn];
    self.connectBtn = connectBtn;
    
    UIButton *disconnectBtn = [[UIButton alloc] initWithFrame:connectBtn.frame];
    [disconnectBtn setTitle:showText(@"断开连接") forState:UIControlStateNormal];
    [disconnectBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    disconnectBtn.hidden = YES;
    disconnectBtn.layer.cornerRadius = 5;
    disconnectBtn.layer.borderColor = [UIColor grayColor].CGColor;
    disconnectBtn.layer.borderWidth = 0.5;
    disconnectBtn.layer.masksToBounds = YES;
    [disconnectBtn addTarget:self action:@selector(disconnctClick) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:disconnectBtn];
    self.disconnectBtn = disconnectBtn;
}

- (void)loadDeviceList
{
    self.deviceArray = [NSMutableArray array];
    self.selectedArray = [NSMutableArray array];
    
    [self.deviceArray removeAllObjects];
    [self.tableView reloadData];
    
    BluetoothManager *blemanager = [BluetoothManager standardManager];
    blemanager.delegate = self;
    [blemanager startDiscoverPeripheral];

}

- (void)updateSelectedArray:(GWPeripheral *)peripheral
{
    [self.tableView.mj_header endRefreshing];
    if (peripheral.is_select) {
        BOOL isExist = NO;
        for (GWPeripheral *eachPerph in self.selectedArray) {
            if ([eachPerph.macAddress isEqualToString:peripheral.macAddress]) {
                isExist = YES;
            }
        }
        if (!isExist) {
            [self.selectedArray addObject:peripheral];
        }
    } else {
        for (GWPeripheral *eachPerph in self.selectedArray) {
            if ([eachPerph.macAddress isEqualToString:peripheral.macAddress]) {
                [self.selectedArray removeObject:eachPerph];
                break;
            }
        }
    }
    
    int count = 0;
    for (GWPeripheral *perph in self.selectedArray) {
        if (perph.peripheral.state == CBPeripheralStateConnected) {
            count ++;
        }
    }
    
    if (count > 0) {
        self.connectBtn.hidden = YES;
        self.disconnectBtn.hidden = NO;
    } else {
        self.connectBtn.hidden = NO;
        self.disconnectBtn.hidden = YES;
    }
    
    [self.tableView reloadData];
}

#pragma mark - btn click events
- (void)connectClick
{
    if (self.selectedArray.count == 0) {
        return;
    }
    
    for (GWPeripheral *perph in self.selectedArray) {
        [[BluetoothManager standardManager] startConnectPeripheralWithName:perph.macAddress];
        perph.is_select = NO;
    }
    
    [self.selectedArray removeAllObjects];
}

- (void)disconnctClick
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL autoClose = [userDefaults boolForKey:kAutoCloseAfterDisconnect];
    
    for (GWPeripheral *perph in self.selectedArray) {
        perph.is_select = NO;
        if (autoClose) {
            NSString *cmd = @"0500";
            [[BluetoothManager standardManager] writeCommad:cmd onDevice:perph.macAddress];
        }
        if (perph.peripheral.state == CBPeripheralStateConnected) {
            [[BluetoothManager standardManager] cancelPeripheralConnection:perph.macAddress];
        }
    }
    [self.selectedArray removeAllObjects];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.deviceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"deviceCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    
    GWPeripheral *peripheral = self.deviceArray[indexPath.row];
    
    NSString *factName = [peripheral.name stringByReplacingOccurrencesOfString:@"CoolLED" withString:@"CROSBY"];
    
    if (peripheral.peripheral.state == CBPeripheralStateConnected) {
        NSString *text = [NSString stringWithFormat:@"%@(%@)",factName, showText(@"已连接")];
        cell.textLabel.text = text;
    } else {
        cell.textLabel.text = factName;
    }
    
    cell.detailTextLabel.text = peripheral.actulMacAddress;
    
    if (peripheral.is_select) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GWPeripheral *periph = [self.deviceArray objectAtIndex:indexPath.row];
    
    periph.is_select = !periph.is_select;
    
    [self updateSelectedArray:periph];
}

#pragma mark - BluetoothManagerDelegate
- (void)didUpdatePeripheralsArray:(NSArray *)array
{
    [self.tableView.mj_header endRefreshing];
    array = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        GWPeripheral *per1 = (GWPeripheral *)obj1;
        GWPeripheral *per2 = (GWPeripheral *)obj2;
        return [per2.RSSI compare:per1.RSSI];
    }];
    [self.deviceArray removeAllObjects];
    [self.deviceArray addObjectsFromArray:array];
    [self.tableView reloadData];
}

- (void)didConnectedPeripheral:(GWPeripheral *)model
{
    [self.tableView.mj_header endRefreshing];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    BOOL autoOpen = [userDefaults boolForKey:kAutoOpenAfterConnect];
    if (autoOpen) {
        NSString *cmd = @"0501";
        [[BluetoothManager standardManager] writeCommad:cmd onDevice:model.macAddress];
    }
    
    [self.tableView reloadData];
}

- (void)didDisconnectPeripheral:(GWPeripheral *)model
{
    
    [self.tableView reloadData];
}

- (void)didFailToConnectPeripheral:(GWPeripheral *)model
{
    
}

@end
